package cn.cloudtogo.server.module.datasource;

import cn.cloudtogo.common.DatasourceDeleteService;
import cn.cloudtogo.common.GendbException;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.RequestHeaderObject;
import cn.cloudtogo.server.atomapi.event.ApiTokenListDeletedEvent;
import cn.cloudtogo.server.mysql.SpringJdbcTemplateContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Service
@Slf4j
public class ExternalDatasourceDeleteService implements DatasourceDeleteService {

    private final ExternalDatasourceDao externalDatasourceDao;
    private final SpringJdbcTemplateContext context;
    private final ApplicationEventPublisher eventPublisher;

    public ExternalDatasourceDeleteService(ExternalDatasourceDao externalDatasourceDao,
                                           SpringJdbcTemplateContext context,
                                           ApplicationEventPublisher eventPublisher) {
        this.externalDatasourceDao = externalDatasourceDao;
        this.context = context;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public void deletes(String openid) {

        List<ExternalDatasourceModel> models = externalDatasourceDao.list(openid);
        models.stream().map(ExternalDatasourceModel::getUuid).forEach(externalDatasourceDao::delete);
        models.stream().map(RequestHeaderObject::ofModel).forEach(context::remove);


        List<String> uuids = models.stream().map(ExternalDatasourceModel::getUuid)
                .collect(Collectors.toList());
        for (String uuid : uuids) {
            eventPublisher.publishEvent(new ApiTokenListDeletedEvent(uuid));
        }

    }

    @Override
    public void delete(String uuid) {
        ExternalDatasourceModel datasource = externalDatasourceDao.query(uuid);
        if (datasource == null) {
            throw new GendbException(String.format("record does not found from '%s'", uuid));
        }
        externalDatasourceDao.delete(uuid);
        context.remove(RequestHeaderObject.ofModel(datasource));

        eventPublisher.publishEvent(new ApiTokenListDeletedEvent(uuid));
    }
}
